<template>
  <el-button text @click="centerDialogVisible = true">新增作者</el-button>
  <el-dialog
      v-model="centerDialogVisible"
      title="新增作者"
      width="30%"
      align-center
      top="0"
      style="min-width: 600px"
  >
    <AddAuthorForm v-model="author"/>

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="centerDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="add">
          确认添加
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>
<script setup>
import {ref, provide, inject} from 'vue'
import AddAuthorForm from "@/components/add/author/AddAuthorForm.vue";
import {addAuthorApi} from "@/apis/author";
import {ElMessage} from "element-plus";

// 新增时，前端传递的是domains而不是domainsStr
const centerDialogVisible = ref(false)
const author = ref({})
const dns = ref('')
provide('dns', dns)
const getPagedAuthors = inject('getPagedAuthors')
const add = () => {
  // 先通过dns字符串获取domains数组
  if (!dns.value) dns.value = ''
  const dnSet = new Set(dns.value.split(';'))
  author.value.domains = []
  dnSet.forEach(dn => {
    dn = dn.trim()
    if (dn) author.value.domains.push({name: dn})
  })
  console.log(author.value)
  addAuthorApi(author.value).then(resp => {
    console.log(resp.data)
    if (resp.data.code === 200) {
      ElMessage.success('添加成功')
      getPagedAuthors()
      centerDialogVisible.value = false // 关闭对话框
      author.value = {} // 清空表格内容
      dns.value = '' // 清空表格内容
    } else {
      ElMessage.error(resp.data.msg)
    }
  })
}
</script>
<style scoped>
.dialog-footer button:first-child {
  margin-right: 10px;
}
</style>
